package com.pactera.asmp.server.service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.pactera.asmp.server.pojo.*;
import com.pactera.asmp.server.vo.QueryMasterListCondition;
import com.pactera.asmp.server.vo.QueryPMDByCondResponse;
import io.swagger.models.auth.In;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.pactera.asmp.server.common.constants.Constants;
import com.pactera.asmp.server.common.constants.DeviceEnum;
import com.pactera.asmp.server.common.constants.OccupyStatus;
import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.dao.MasterComputerMapper;
import com.pactera.asmp.server.dao.ProjectMapper;
import com.pactera.asmp.server.dao.TProjectMasterComputerDbcMapper;
import com.pactera.asmp.server.dao.TaskDeviceMapper;
import com.pactera.asmp.server.dao.TaskMapper;
import com.pactera.asmp.server.entity.MasterComputerDTO;
import com.pactera.asmp.server.entity.MasterComputerSearchDTO;
import com.pactera.asmp.server.entity.ProjectMasterDeviceVo;
import com.pactera.asmp.server.entity.ResponseResult;
import com.pactera.asmp.server.entity.TaskDevice;
import com.pactera.asmp.server.entity.TaskDeviceExample;
import com.pactera.asmp.server.utils.AssertUtil;
import com.pactera.asmp.server.utils.PageDataResult;

/**
 * @ProjectName: asmp-server
 * @Package com.pactera.asmp.server.service
 * @ClassName: MasterComputerServiceImpl
 * @Description: MasterComputerServiceImpl
 * @Date 2020/06/28 17:03
 * @Author lvzhiqiang
 * @Version 1.0
 */
@Service
public class MasterComputerServiceImpl implements IMasterComputerServcie {

    @Autowired
    public ProjectMapper mProjectMapper;

    @Autowired
    private MasterComputerMapper mMasterComputerMapper;

    @Autowired
    private TokenServiceImpl mTokenService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDeviceMapper taskDeviceMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TProjectMasterComputerDbcMapper projectMasterComputerDbcMapper;

    private static final Logger logger = LoggerFactory.getLogger(MasterComputerServiceImpl.class);

    @Override
    public boolean insert(MasterComputerDTO masterComputerDTO) {
        MasterComputer masterComputer = new MasterComputer();
        masterComputer.setCuid(masterComputerDTO.getCuid());
        masterComputer.setIp(masterComputerDTO.getIp());
        masterComputer.setMac(masterComputerDTO.getMac());
        masterComputer.setName(masterComputerDTO.getName());
        masterComputer.setOsType(masterComputerDTO.getOsType());
        masterComputer.setRegisterTime(new Date());
        return mMasterComputerMapper.insert(masterComputer) > 0;
    }

    @Override
    public boolean delete(Integer id) {
        MasterComputer masterComputer = mMasterComputerMapper.selectByPrimaryKey(id);
        if(masterComputer!=null) {
            masterComputer.setIsDeleted(1);
            mMasterComputerMapper.update(masterComputer);
        }
        return true;
    }

    @Override
    public boolean delete(List<Integer> datas) {
        if(CollectionUtils.isNotEmpty(datas)){
            for(Integer id: datas){
                delete(id);
            }
        }
        return true;
    }

    @Override
    public boolean update(MasterComputer masterComputer) {
        return mMasterComputerMapper.update(masterComputer) > 0;
    }

    @Override
    public boolean updateRegister(MasterComputerDTO masterComputer) {
        return mMasterComputerMapper.updateRegister(masterComputer) > 0;
    }

    @Override
    public MasterComputer get(Integer id) {
        return mMasterComputerMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageDataResult get(MasterComputerSearchDTO masterComputerSearchDTO, int page, int limit) {
        PageDataResult pageDataResult = new PageDataResult();
        PageHelper.startPage(page, limit);
        List<MasterComputer> list = mMasterComputerMapper.getMasterComputer(masterComputerSearchDTO);
        PageInfo<MasterComputer> pageInfo = new PageInfo<>(list);
        pageDataResult.setTotals((int) pageInfo.getTotal());
        pageDataResult.setList(list);
        return pageDataResult;
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        return mMasterComputerMapper.updateStatusByPrimaryKey(id, status) > 0;
    }

    @Override
    public MasterComputer selectIdByCuid(String cuid, String mac) {
        return mMasterComputerMapper.selectIdByCuid(cuid, mac);
    }

    @Override
    @Transactional
    public ResponseResult registerMasterComputer(MasterComputerDTO masterComputerDTO) {
        ResponseResult responseResult;
        if (null == masterComputerDTO) {
            return new ResponseResult(ResultCode.PARAM_IS_BLANK);
        }
        if (StringUtils.isEmpty(masterComputerDTO.getCuid()) || StringUtils.isEmpty(masterComputerDTO.getMac())) {
            return new ResponseResult(ResultCode.PARAM_NOT_COMPLETE);
        }
        MasterComputer masterComputer = this.selectIdByCuid(masterComputerDTO.getCuid(), masterComputerDTO.getMac());
        if (masterComputer != null) {

            if(!StringUtils.isEmpty(masterComputerDTO.getName()) && !masterComputerDTO.getName().equalsIgnoreCase(masterComputer.getName())
                    || !StringUtils.isEmpty(masterComputerDTO.getIp()) && !masterComputerDTO.getName().equalsIgnoreCase(masterComputer.getIp())
                    || !StringUtils.isEmpty(masterComputerDTO.getOsType()) && !masterComputerDTO.getName().equalsIgnoreCase(masterComputer.getOsType())){
                masterComputerDTO.setId(masterComputer.getId());
                this.updateRegister(masterComputerDTO);
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", masterComputer.getId());
            String token = mTokenService.createToken(String.valueOf(masterComputer.getId()), "0", DeviceEnum.MASTER_COMPUTER_DEVICE.getChannelId());
            jsonObject.put("token", token);
            responseResult = new ResponseResult(ResultCode.SUCCESS);
            responseResult.setData(jsonObject);
            return responseResult;
        }

        boolean result = this.insert(masterComputerDTO);
        if (result) {
            int id = this.selectIdByCuid(masterComputerDTO.getCuid(), masterComputerDTO.getMac()).getId();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", id);
            String token = mTokenService.createToken(String.valueOf(id), "0", DeviceEnum.MASTER_COMPUTER_DEVICE.getChannelId());
            jsonObject.put("token", token);
            responseResult = new ResponseResult(ResultCode.SUCCESS);
            responseResult.setData(jsonObject);
        } else {
            responseResult = new ResponseResult(ResultCode.FAIL);
        }
        return responseResult;
    }

    @Override
    public ResponseResult<List<MasterComputer>> getMastercList() {
        return ResponseResult.defaultSuccess(mMasterComputerMapper.getMasterComputer(new MasterComputerSearchDTO()));
    }

    @Override
    public int updateNickName(MasterComputer masterComputer) {
        AssertUtil.notNull(masterComputer,"参数异常");
        AssertUtil.notNull(masterComputer.getId(),"上位机ID不允许为空");
        AssertUtil.hasText(masterComputer.getNickName(),"昵称不允许为空");
        AssertUtil.isTrue(masterComputer.getNickName().matches(Constants.REGEXP_FIRST_LAST_NOT_SPACE),"昵称格式不正确");
        return mMasterComputerMapper.updateNickName(masterComputer);
    }

    @Override
    public ResponseResult<List<MasterComputer>> getMastercListByProjectId(Integer projectId) {
        return ResponseResult.defaultSuccess(mMasterComputerMapper.getMasterComputerByProjectId(projectId));
    }

    @Override
    public List<ProjectMasterDeviceVo> mastercBindByProjectId(Integer projectId) {
        AssertUtil.notNull(projectId,"项目ID不允许为空");
        List<ProjectMasterDeviceVo> list = mMasterComputerMapper.mastercBindByProjectId(projectId);
        // 统计后排序
        if(!CollectionUtils.isEmpty(list)){
               for(ProjectMasterDeviceVo vo : list){
                   if(!CollectionUtils.isEmpty(vo.getDeviceInfos()) && (vo.getMasterComputer().getProjectId() != null && vo.getMasterComputer().getProjectId() != 0)){
                       vo.getMasterComputer().setProDeviceCount(vo.getDeviceInfos().size());
                   }else {
                       vo.getMasterComputer().setProDeviceCount(0);
                   }
               }
               Collections.sort(list);
        }
        return list;
    }

    @Override
    public List<ProjectMasterDeviceVo> listBindByProjectId(Integer projectId, Integer masterComputerId) {
        AssertUtil.notNull(projectId,"项目ID不允许为空");
        List<ProjectMasterDeviceVo> projectMasterDeviceVos = mMasterComputerMapper.listBindByProjectId(projectId, masterComputerId, userService.getRelatedProject());
        if(CollectionUtils.isEmpty(projectMasterDeviceVos)) {
            return projectMasterDeviceVos;
        }

        projectMasterDeviceVos = projectMasterDeviceVos.stream().filter(x -> CollectionUtils.isNotEmpty(x.getDeviceInfos())).collect(Collectors.toList());
        List<Integer> masterComputerIds = projectMasterDeviceVos.stream().map(x -> x.getMasterComputer().getId()).distinct().collect(Collectors.toList());
        Map<Integer, List<ProjectInfo>> projectListMap = Maps.newHashMap();
        if((null == projectId || 0 == projectId.intValue())
                && CollectionUtils.isNotEmpty(masterComputerIds)) {
            TProjectMasterComputerDbcExample example = new TProjectMasterComputerDbcExample();
            example.createCriteria().andMasterComputerIdIn(masterComputerIds);
            List<TProjectMasterComputerDbc> dbcList = projectMasterComputerDbcMapper.selectByExample(example);
            List<Integer> projectIds = dbcList.stream().map(TProjectMasterComputerDbc::getProjectId).distinct().collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(projectIds)) {
                List<ProjectInfo> projectInfos = mProjectMapper.queryByPrimaryKeys(projectIds);
                Map<Integer, ProjectInfo> projectInfoMap = projectInfos.stream().collect(Collectors.toMap(ProjectInfo::getId, v -> v));
                Map<Integer, List<TProjectMasterComputerDbc>> dcListMap = dbcList.stream().collect(Collectors.groupingBy(TProjectMasterComputerDbc::getMasterComputerId));
                for(Integer cuid : dcListMap.keySet()) {
                    List<TProjectMasterComputerDbc> list = dcListMap.get(cuid);
                    if(CollectionUtils.isNotEmpty(list)) {
                        projectListMap.put(cuid, list.stream().map(x -> projectInfoMap.get(x.getProjectId())).filter(x -> null != x).collect(Collectors.toList()));
                    }
                }
            }
            
        }
        projectMasterDeviceVos.stream().forEach(projectMasterDeviceVo ->{
            if((null == projectId || 0 == projectId.intValue()) && MapUtils.isNotEmpty(projectListMap)) {
                projectMasterDeviceVo.getMasterComputer().setProjectInfos(projectListMap.get(projectMasterDeviceVo.getMasterComputer().getId()));
            }
            if(CollectionUtils.isNotEmpty(projectMasterDeviceVo.getDeviceInfos())) {
                projectMasterDeviceVo.getDeviceInfos().stream().forEach(deviceInfo -> {

                    String canCode = deviceInfo.getCanCode();
                    if (StringUtils.isNotBlank(canCode)) {
                        deviceInfo.setCanState(Constants.CAN_INFO_STATE_2);
                        String redisKey = new StringBuilder(Constants.REDIS_KEY_PREFIX_CAN_BIND).append("_")
                                .append(deviceInfo.getCuid()).append("_")
                                .append(deviceInfo.getCanCode()).append("_")
                                .append(deviceInfo.getDuid()).toString();
                        if (redisTemplate.hasKey(redisKey).booleanValue()) {
                            deviceInfo.setCanState(Constants.CAN_INFO_STATE_1);
                        }
                    }
                    // 占用时查看是否被任务占用
                    if(deviceInfo.getStatus() == 1) {
                        if(deviceInfo.getIsAuxiliary().intValue() == 0) {
                            TaskDeviceExample example =new TaskDeviceExample();
                            example.createCriteria().andDuidEqualTo(deviceInfo.getDuid()).andOccupyStatusEqualTo(OccupyStatus.OCCUPIED.getValue()).andIsDeletedEqualTo(0);
                            List<TaskDevice> taskDevices = taskDeviceMapper.selectByExample(example);
                            if(CollectionUtils.isNotEmpty(taskDevices)) {
                                deviceInfo.setTaskDTO(taskMapper.getTaskHistoryById(taskDevices.get(0).getTaskId().intValue()));
                            }
                        }else {
                            TaskDeviceExample example =new TaskDeviceExample();
                            example.or().andDuidEqualTo(deviceInfo.getDuid()).andOccupyStatusEqualTo(OccupyStatus.OCCUPIED.getValue()).andIsDeletedEqualTo(0);
                            example.or().andAuxDuidEqualTo(deviceInfo.getDuid()).andOccupyStatusEqualTo(OccupyStatus.OCCUPIED.getValue()).andIsDeletedEqualTo(0);
                            List<TaskDevice> taskDevices = taskDeviceMapper.selectByExample(example);
                            if(CollectionUtils.isNotEmpty(taskDevices)) {
                                deviceInfo.setTaskDTO(taskMapper.getTaskHistoryById(taskDevices.get(0).getTaskId().intValue()));
                            }
                        }
                    }
                });
            }
        });
        return projectMasterDeviceVos.stream().sorted((v1, v2) -> {
            if(v1.getDeviceInfos().stream().anyMatch(x -> x.getStatus() == 0)) {
                return -1;
            }
            if(v2.getDeviceInfos().stream().anyMatch(x -> x.getStatus() == 0)) {
                return 1;
            }
            return 0;
        }).collect(Collectors.toList());
    }

    @Override
    public QueryPMDByCondResponse listBindByCondition(QueryMasterListCondition condition) {
        QueryPMDByCondResponse response = new QueryPMDByCondResponse();
        try {
            List<ProjectMasterDeviceVo> projectMasterDeviceVos = mMasterComputerMapper.listBindByProjectId(condition.getProjectId().intValue(), null, userService.getRelatedProject());
            if (CollectionUtils.isEmpty(projectMasterDeviceVos)) {
                return response;
            }

            projectMasterDeviceVos = projectMasterDeviceVos.stream().filter(x -> CollectionUtils.isNotEmpty(x.getDeviceInfos())).collect(Collectors.toList());
            if (StringUtils.isNotBlank(condition.getMasterName())) {
                projectMasterDeviceVos = projectMasterDeviceVos.stream().filter(x -> x.getMasterComputer().getName().contains(condition.getMasterName())).collect(Collectors.toList());
            }
            List<Integer> masterComputerIds = projectMasterDeviceVos.stream().map(x -> x.getMasterComputer().getId()).distinct().collect(Collectors.toList());
            Map<Integer, List<ProjectInfo>> projectListMap = Maps.newHashMap();
            if ((null == condition.getProjectId() || 0 == condition.getProjectId().intValue())
                    && CollectionUtils.isNotEmpty(masterComputerIds)) {
                TProjectMasterComputerDbcExample example = new TProjectMasterComputerDbcExample();
                example.createCriteria().andMasterComputerIdIn(masterComputerIds);
                List<TProjectMasterComputerDbc> dbcList = projectMasterComputerDbcMapper.selectByExample(example);
                List<Integer> projectIds = dbcList.stream().map(TProjectMasterComputerDbc::getProjectId).distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(projectIds)) {
                    List<ProjectInfo> projectInfos = mProjectMapper.queryByPrimaryKeys(projectIds);
                    Map<Integer, ProjectInfo> projectInfoMap = projectInfos.stream().collect(Collectors.toMap(ProjectInfo::getId, v -> v));
                    Map<Integer, List<TProjectMasterComputerDbc>> dcListMap = dbcList.stream().collect(Collectors.groupingBy(TProjectMasterComputerDbc::getMasterComputerId));
                    for (Integer cuid : dcListMap.keySet()) {
                        List<TProjectMasterComputerDbc> list = dcListMap.get(cuid);
                        if (CollectionUtils.isNotEmpty(list)) {
                            projectListMap.put(cuid, list.stream().map(x -> projectInfoMap.get(x.getProjectId())).filter(x -> null != x).collect(Collectors.toList()));
                        }
                    }
                }

            }
            projectMasterDeviceVos.stream().forEach(projectMasterDeviceVo -> {
                if ((null == condition.getProjectId() || 0 == condition.getProjectId().intValue()) && MapUtils.isNotEmpty(projectListMap)) {
                    projectMasterDeviceVo.getMasterComputer().setProjectInfos(projectListMap.get(projectMasterDeviceVo.getMasterComputer().getId()));
                }
                if (CollectionUtils.isNotEmpty(projectMasterDeviceVo.getDeviceInfos())) {
                    projectMasterDeviceVo.getDeviceInfos().stream().forEach(deviceInfo -> {

                        String canCode = deviceInfo.getCanCode();
                        if (StringUtils.isNotBlank(canCode)) {
                            deviceInfo.setCanState(Constants.CAN_INFO_STATE_2);
                            String redisKey = new StringBuilder(Constants.REDIS_KEY_PREFIX_CAN_BIND).append("_")
                                    .append(deviceInfo.getCuid()).append("_")
                                    .append(deviceInfo.getCanCode()).append("_")
                                    .append(deviceInfo.getDuid()).toString();
                            if (redisTemplate.hasKey(redisKey).booleanValue()) {
                                deviceInfo.setCanState(Constants.CAN_INFO_STATE_1);
                            }
                        }
                        // 占用时查看是否被任务占用
                        if (deviceInfo.getStatus() == 1) {
                            if (deviceInfo.getIsAuxiliary().intValue() == 0) {
                                TaskDeviceExample example = new TaskDeviceExample();
                                example.createCriteria().andDuidEqualTo(deviceInfo.getDuid()).andOccupyStatusEqualTo(OccupyStatus.OCCUPIED.getValue()).andIsDeletedEqualTo(0);
                                List<TaskDevice> taskDevices = taskDeviceMapper.selectByExample(example);
                                if (CollectionUtils.isNotEmpty(taskDevices)) {
                                    deviceInfo.setTaskDTO(taskMapper.getTaskHistoryById(taskDevices.get(0).getTaskId().intValue()));
                                }
                            } else {
                                TaskDeviceExample example = new TaskDeviceExample();
                                example.or().andDuidEqualTo(deviceInfo.getDuid()).andOccupyStatusEqualTo(OccupyStatus.OCCUPIED.getValue()).andIsDeletedEqualTo(0);
                                example.or().andAuxDuidEqualTo(deviceInfo.getDuid()).andOccupyStatusEqualTo(OccupyStatus.OCCUPIED.getValue()).andIsDeletedEqualTo(0);
                                List<TaskDevice> taskDevices = taskDeviceMapper.selectByExample(example);
                                if (CollectionUtils.isNotEmpty(taskDevices)) {
                                    deviceInfo.setTaskDTO(taskMapper.getTaskHistoryById(taskDevices.get(0).getTaskId().intValue()));
                                }
                            }
                        }
                    });
                }
            });
            List<ProjectMasterDeviceVo> list = projectMasterDeviceVos.stream().sorted((v1, v2) -> {
                if (v1.getDeviceInfos().stream().anyMatch(x -> x.getStatus() == 0)) {
                    return -1;
                }
                if (v2.getDeviceInfos().stream().anyMatch(x -> x.getStatus() == 0)) {
                    return 1;
                }
                return 0;
            }).collect(Collectors.toList());
            List<ProjectMasterDeviceVo> rsltList = new ArrayList<>();
            Iterator<ProjectMasterDeviceVo> iterator = list.iterator();
            while (iterator.hasNext()) {
                ProjectMasterDeviceVo pmd = iterator.next();
                if (condition.getStatus() != null) {
                    boolean contain = false;
                    List<DeviceInfoWithProject> deviceInfos = pmd.getDeviceInfos();
                    for(DeviceInfoWithProject device: deviceInfos){
                        if (device.getStatus() == condition.getStatus()) {
                            contain = true;
                        }
                        if(condition.getStatus() == 0 && device.getStatus() == 1){
                            contain = false;
                            break;
                        }
                    }
                    if(!contain){
                        iterator.remove();
                        continue;
                    }
                }
                boolean contain = false;
                if (StringUtils.isNotBlank(condition.getText())) {
                    String masterName = pmd.getMasterComputer().getName();
                    if (StringUtils.isNotBlank(masterName)
                            && masterName.contains(condition.getText())) {
                        continue;
                    }
                    List<DeviceInfoWithProject> deviceInfos = pmd.getDeviceInfos();
                    for (DeviceInfoWithProject device : deviceInfos) {
                        if (StringUtils.isNotBlank(device.getBrand())
                                && device.getBrand().contains(condition.getText())) {
                            contain = true;
                            break;
                        }
                        if (!StringUtils.isNotBlank(device.getModel())
                                && device.getModel().contains(condition.getText())) {
                            contain = true;
                            break;
                        }
                    }
                    if (!contain) {
                        iterator.remove();
                    }
//                    else {
//                        rsltList.add(pmd);
//                    }
                }
            }
            for (ProjectMasterDeviceVo pmd : projectMasterDeviceVos) {
                List<DeviceInfoWithProject> deviceInfos = pmd.getDeviceInfos();
                for (DeviceInfoWithProject device : deviceInfos) {
                    if (device.getStatus() == 0) {
                        response.getIdleDevices().add(device);
                    }
                    if (device.getStatus() == 1) {
                        response.getUsingDevices().add(device);
                    }
                }
                boolean isUsing = false;
                for (DeviceInfoWithProject device : deviceInfos) {
                    if (device.getStatus() == 1) {
                        response.setUsingMasterCount(response.getUsingMasterCount()+1);
                        isUsing = true;
                        break;
                    }

                }
                if(!isUsing){
                    for (DeviceInfoWithProject device : deviceInfos) {
                        if (device.getStatus() == 0) {
                            response.setIdleMasterCount(response.getIdleMasterCount()+1);
                            break;
                        }
                    }
                }
            }
            for(ProjectMasterDeviceVo pmd : list){
                response.getMList().add(pmd.getMasterComputer());
            }
            response.setIdleCount(response.getIdleDevices().size());
            response.setUsingCount(response.getUsingDevices().size());
            response.setMCount(projectMasterDeviceVos.size());
            response.setPmdList(list);

            for(ProjectMasterDeviceVo pmd:list){
                List<DeviceInfoWithProject> sortdeviceInfos = new ArrayList<>();
                List<DeviceInfoWithProject> deviceInfos = pmd.getDeviceInfos();
                for(DeviceInfoWithProject dwp:deviceInfos){
                    if(dwp.getIsAuxiliary() == 0){
                        sortdeviceInfos.add(dwp);
                    }
                }
                for(DeviceInfoWithProject dwp:deviceInfos){
                    if(dwp.getIsAuxiliary() != 0){
                        sortdeviceInfos.add(dwp);
                    }
                }
                pmd.setDeviceInfos(sortdeviceInfos);
            }
        }catch (Exception e){
            logger.error("listBindByCondition error ",e);
        }
        return response;
    }

    public QueryPMDByCondResponse mastercBindByCondition(QueryMasterListCondition condition) {
        AssertUtil.notNull(condition,"condition不允许为空");
        QueryPMDByCondResponse response = new QueryPMDByCondResponse();
        List<ProjectMasterDeviceVo> list = mMasterComputerMapper.mastercBindByProjectId(condition.getProjectId().intValue());
        // 统计后排序
        if(!CollectionUtils.isEmpty(list)){
            for(ProjectMasterDeviceVo vo : list){
                if(!CollectionUtils.isEmpty(vo.getDeviceInfos()) && (vo.getMasterComputer().getProjectId() != null && vo.getMasterComputer().getProjectId() != 0)){
                    vo.getMasterComputer().setProDeviceCount(vo.getDeviceInfos().size());
                }else {
                    vo.getMasterComputer().setProDeviceCount(0);
                }
            }
            Collections.sort(list);
        }
        List<ProjectMasterDeviceVo> projectMasterDeviceVos = new ArrayList<>();
        projectMasterDeviceVos.addAll(list);
        Iterator<ProjectMasterDeviceVo> iterator = list.iterator();
        while(iterator.hasNext()){
            ProjectMasterDeviceVo pmd = iterator.next();
            if(condition.getStatus() != null){
                boolean contain = false;
                List<DeviceInfoWithProject> deviceInfos = pmd.getDeviceInfos();
                for(DeviceInfoWithProject device: deviceInfos){
                    if (device.getStatus() == condition.getStatus()) {
                        contain = true;
                    }
                    if(condition.getStatus() == 0 && device.getStatus() == 1){
                        contain = false;
                        break;
                    }
                }
                if(!contain){
                    iterator.remove();
                }
            }
            boolean contain = false;
            if(StringUtils.isNotBlank(condition.getText())){
                String masterName = pmd.getMasterComputer().getName();
                if(StringUtils.isNotBlank(masterName)
                        && masterName.contains(condition.getText())){
                    continue;
                }
                List<DeviceInfoWithProject> deviceInfos = pmd.getDeviceInfos();
                for(DeviceInfoWithProject device: deviceInfos){
                    if (StringUtils.isNotBlank(device.getBrand())
                            && device.getBrand().contains(condition.getText())) {
                        contain = true;
                        break;
                    }
                    if (StringUtils.isNotBlank(device.getModel())
                            && device.getModel().contains(condition.getText())) {
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    iterator.remove();
                }
            }
        }
        for (ProjectMasterDeviceVo pmd : projectMasterDeviceVos) {
            List<DeviceInfoWithProject> deviceInfos = pmd.getDeviceInfos();
            for (DeviceInfoWithProject device : deviceInfos) {
                if (device.getStatus() == 0) {
                    response.getIdleDevices().add(device);
                }
                if (device.getStatus() == 1) {
                    response.getUsingDevices().add(device);
                }
            }
            boolean isUsing = false;
            for (DeviceInfoWithProject device : deviceInfos) {
                if (device.getStatus() == 1) {
                    response.setUsingMasterCount(response.getUsingMasterCount()+1);
                    isUsing = true;
                    break;
                }

            }
            if(!isUsing){
                for (DeviceInfoWithProject device : deviceInfos) {
                    if (device.getStatus() == 0) {
                        response.setIdleMasterCount(response.getIdleMasterCount()+1);
                        break;
                    }
                }
            }
        }
        for(ProjectMasterDeviceVo pmd : list){
            response.getMList().add(pmd.getMasterComputer());
        }
        response.setIdleCount(response.getIdleDevices().size());
        response.setUsingCount(response.getUsingDevices().size());
        response.setMCount(projectMasterDeviceVos.size());
        response.setPmdList(list);
        return response;
    }

}
